import React from 'react'

import './css/Position_Picker.css'

import * as DataHandler from './DataHandler'

/* 拖拽选址 */
class Position_Picker extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            display: ''
        }
    }
    componentDidMount = () => {
        this.reload();
    }

    resume = () => {
        this.reload();
    }

    reload = () => {
        // this.initPosition();

        // 设置地图容器高度
        document.getElementById('container').style.height = (document.documentElement.clientHeight || document.body.clientHeight) + 'px';
        // 获得定位坐标
        let center = DataHandler.getPosition();
        // 初始化定位地址
        // T.data('Position_Picker_Result', {address: center.address});
        let latng = T.data('Position_Picker') ? T.data('Position_Picker').latng : ['120.102398', '30.867198'];
        // 初始化定位地图
        DataHandler.initPicker(latng);

        this.setState({display: ''});
    }

    initPosition = () => {
        let timer = setInterval(() => {
            let __rnWebview = window.__rnWebview;
            // 判断对象和方法是否存在
            if(__rnWebview && __rnWebview.getGeolocation) {
                // 对象存在即可清除定时器
                clearInterval(timer);
        
                // 订阅定位事件
                __rnWebview.subscribe(__rnWebview.listeners.geolocation, this.geolocation);
        
                // 调用定位方法，定位成功后会触发定位事件
                // object 参数 
                // {
                //      openGps: false // 检测GPS是否开启，默认不检测
                // }
                __rnWebview.getGeolocation({openGps: false});
            }
        }, 100);
    }

    geolocation = (msg, data) => {
        alert(msg.coordinate.longitude, msg.coordinate.latitude)
    }

    /* 动态加载地图api */
    addScriptTag = (src, method) => {
        let script = document.createElement('script');  
        script.setAttribute("type","text/javascript");
        if(method){
            script.setAttribute('async', true);
        }
        script.src = src;  
        document.body.appendChild(script);  
    }
    
    //解析定位结果
    onComplete(data) {
        console.log({
            lng: `经度：${data.position.getLng()}`,
            lat: `纬度：${data.position.getLat()}`,
            accuracy: `精度：${data.accuracy?data.accuracy:null}`,
            isConverted: `是否经过偏移：${data.isConverted?'是':'否'}`
        });
    }
    //解析定位错误信息
    onError(data) {
        console.log(data)
    }

    back = () => {
        this.setState({display: 'none'});
        document.getElementById('container').style.height = 0;
        T.router.go('/'+T.data('Position_Picker').parent);
    }

    render() {
        const {display} = this.state;

        return (
            <div className='Position_Picker'>
                <div className='back' style={{display}} onClick={this.back}>&lt;返回</div>
            </div>
        )
    }
}

export default Position_Picker
